import React, { Component } from 'react';
import { connect } from 'react-redux';
import CustomForm from '../../../components/CustomForm';
import { Input, message, Select, Button, Tooltip } from 'antd';
import services from '../../../services/api';
import OnlinePolicy from './onlinePolicy';
import AddPolicy from '../../Strategy/Strategy/add';
import { cloneDeep } from 'lodash';
import AddList from './addList';
import Modal from '../../../components/Modal';
import { STRATEGY_TYPE } from '../../../utils/constant';
import './index.less';

const Option = Select.Option;

function mapStateToProps(state) {
  return {
    strategy_type: state.code.strategy_type || [],
    strategy_mode: state.code.strategy_mode || [],
  };
}

@connect(mapStateToProps)
class LabsAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formItems: [],
      applications: [],
      products: [],
      events: [],
      lab_id: props.match.params.id,
      app_id: '',
      event_id: '',
      strategy_list: [],
      strategy_data: [], // 原始数据
      editIndex: '',
    };
    this.actionType = 'add';
    this.form = null;
    this.copyForm = null;
    this.api = 'strategyLabsApi';
    this.initQueryPanigation = {
      current_page: 1,
      page_size: 10,
    };
  }

  componentDidMount() {
    this.props.dispatch({ type: 'pageClose/waringAdd' });
    this.getAppCodeList();
    this.getProductCodeList({});
    if (this.state.lab_id) {
      this.actionType = 'update';
      this.getLabDetail();
    }
  }

  componentWillUnmount() {
    this.props.dispatch({ type: 'pageClose/waringReduce' });
  }

  changeName = (name) => {
    const arr = name.split('_副本_');
    return arr[0] + '_副本_' + new Date().getTime();
  };
  changeCode = (code) => {
    const arr = code.split('_copy_');
    return arr[0] + '_copy_' + new Date().getTime();
  };
  getAppCodeList = () => {
    services.application.getAppCodeList({}).then((res) => {
      if (res.code === 0) {
        this.setState({
          applications: res.data,
        });
      }
    });
  };

  // 业务挂钩的，产品列表请求
  getProductCodeList = ({ app_id, event_id }) => {
    services.product.getProductCodeList(event_id ? { app_id, event_id } : {}).then((res) => {
      if (res.code === 0) {
        this.setState(
          {
            products: res.data,
          },
          () => {
            // 当event_id存在，默认回写productId
            if (event_id) {
              const p_id = res.data.length === 1 ? res.data[0].product_id : undefined;
              this.setState({
                product_id: p_id,
              });
              this.form.setFieldsValue({ product_id: p_id });
            }
          }
        );
      }
    });
  };

  getEventCodeList = ({ app_id, product_id } = {}) => {
    const params = {};
    if (app_id) {
      params.app_id = app_id;
    }
    if (product_id) {
      params.product_id = product_id;
    }
    services.event.getEventCodeList(params).then((res) => {
      if (res.code === 0) {
        this.setState({
          events: res.data,
        });
      }
    });
  };

  getLabDetail = () => {
    services[this.api].detailList({ lab_id: this.state.lab_id }).then((res) => {
      if (res.code === 0) {
        const app_id = res.data.app_id;
        const product_id = res.data.product_id;
        const strategy_data = cloneDeep(res.data.strategy_list);
        if (strategy_data && strategy_data.length > 0) {
          strategy_data[0].name =
            strategy_data[0].name.substr(0, strategy_data[0].name.indexOf('_副本')) || strategy_data[0].name;
        }
        this.getEventCodeList({ app_id, product_id });
        this.setState({
          ...res.data,
          strategy_data,
        });
      } else {
        message.error(res.msg);
      }
    });
  };

  handleConfirmBlur = (e) => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  appChange = (app_id) => {
    this.setState(
      {
        app_id,
        event_id: undefined,
        strategy_list: [],
      },
      this.getEventCodeList({ app_id, product_id: this.form.getFieldValue('product_id') || undefined })
    );
    this.form.setFieldsValue({ event_id: undefined });
  };

  productChange = (product_id) => {
    this.setState(
      {
        product_id,
        event_id: undefined,
        strategy_list: [],
      },
      () => {
        if (!product_id) {
          this.getProductCodeList({});
        }
        this.getEventCodeList({ product_id, app_id: this.form.getFieldValue('app_id') || undefined });
        this.form.setFieldsValue({ event_id: undefined });
      }
    );
  };

  eventChange = (event_id) => {
    this.setState({ event_id }, this.getProductCodeList({ app_id: this.state.app_id, event_id: event_id }));
  };

  openOnlinePolicy = () => {
    if (this.state.strategy_list.length) {
      message.warning('添加失败：当前试验项已存在实验策略，请先删除！');
      return;
    }
    const app_id = this.form.getFieldValue('app_id');
    const event_id = this.form.getFieldValue('event_id');
    if (!app_id || !event_id) {
      message.error('请先选择渠道和事件再进行操作');
    } else {
      Modal.open({
        title: '引用试验策略（可引用线上同渠道、事件下的策略）',
        width: this.model_width ? this.model_width : '1000px',
        content: (
          <OnlinePolicy {...this.props} {...this.state} sureQuote={this.sureQuote} closeModal={() => Modal.close()} />
        ),
        isOkBtn: false,
        maskClosable: false,
        isCancelBtn: false,
      });
    }
  };
  getPolicyByIds = (strategy_ids) => {
    services[this.api].getPolicyByIds({ strategy_ids }).then((res) => {
      if (res.code === 0) {
        const lists = cloneDeep(res.data);
        this.setState({
          strategy_data: res.data,
          strategy_list: [
            ...lists.map((item) => {
              item.name = this.changeName(JSON.parse(JSON.stringify(item.name)));
              item.code = item.code + '_copy_' + new Date().getTime();
              return item;
            }),
            // ...res.data.map((item) => {
            //   let config = {};
            //   // 如果是普通策略
            //   if (item.strategy_type === STRATEGY_TYPE._COMMON) {
            //     const rules =
            //       (item.strategy_config && item.strategy_config.mode && item.strategy_config.mode.rules) || [];
            //     const code =
            //       (item.strategy_config && item.strategy_config.mode && item.strategy_config.mode.code) || [];
            //     const newRules = this.removeRuleId(Object.assign([], rules));
            //     config = {
            //       ...item,
            //       strategy_config: {
            //         ...item.strategy_config,
            //         mode: {
            //           ...(item.strategy_config && item.strategy_config.mode),
            //           code,
            //           rules: newRules,
            //         },
            //       },
            //       name: this.changeName(item.name),
            //       strategy_id: undefined,
            //     };
            //   } else {
            //     const nodes = item.strategy_config.nodes && item.strategy_config.nodes.map((item) => {
            //       // 如果是策略节点，则需要做处理
            //       if (item.type === 'strategy') {
            //         const rules =
            //           (item.strategy_config && item.strategy_config.mode && item.strategy_config.mode.rules) || [];
            //         const code =
            //           (item.strategy_config && item.strategy_config.mode && item.strategy_config.mode.code) || [];
            //         const newRules = this.removeRuleId(Object.assign([], rules));
            //         return {
            //           ...item,
            //           strategy_config: {
            //             ...item.strategy_config,
            //             mode: {
            //               ...(item.strategy_config && item.strategy_config.mode),
            //               code,
            //               rules: newRules,
            //             },
            //           },
            //         };
            //       } else {
            //         return item;
            //       }
            //     });
            //     config = {
            //       ...item,
            //       strategy_config: {
            //         edges: item.strategy_config.edges,
            //         nodes,
            //       },
            //       name: this.changeName(item.name),
            //       strategy_id: undefined,
            //     };
            //   }
            //   return config;
            // }),
            ...this.state.strategy_list,
          ],
        });
        Modal.close();
      } else {
        message.error(res.msg);
      }
    });
  };
  sureQuote = (selectedRowKeys) => {
    this.getPolicyByIds(selectedRowKeys);
  };

  openAddPolicy = () => {
    if (this.state.strategy_list.length) {
      message.warning('添加失败：当前试验项已存在实验策略，请先删除！');
      return;
    }
    const app_id = this.form.getFieldValue('app_id');
    const event_id = this.form.getFieldValue('event_id');
    const product_id = this.form.getFieldValue('product_id');
    if (!app_id || !event_id) {
      message.error('请先选择渠道和事件再进行操作');
    } else {
      this.setState({
        editIndex: '',
      });
      Modal.open({
        title: '新建试验策略',
        width: this.model_width ? this.model_width : '1200px',
        content: (
          <div className='stretegy-content' style={{ marginTop: '-10px' }}>
            <AddPolicy
              {...this.props}
              {...this.state}
              isDisable={true}
              usePolicy={(data) => this.usePolicy(data)}
              closeModal={() => Modal.close()}
              actionType='add'
              localSubmit={true}
              value={{
                app_id,
                event_id,
                product_id,
                strategy_type: STRATEGY_TYPE._COMMON,
                strategy_config: {},
              }}
            />
          </div>
        ),
        isOkBtn: false,
        maskClosable: false,
        isCancelBtn: false,
      });
    }
  };

  checkPolicyData = async (policy) => {
    return await services.strategyLabsApi.validate(policy).then((res) => {
      if (res.code === 0) {
        return true;
      } else {
        message.error(res.msg);
        return false;
      }
    });
  };

  usePolicy = async (policy, id) => {
    policy.product_id = policy.product_id || 0;
    policy.strategy_type = 2;
    policy.strategy_mode = 6;
    policy.version = 1;
    // policy.name = this.changeName(policy.name)
    const params = id ? { strategy_id: id, ...policy } : policy;
    const result = await this.checkPolicyData(params);
    // 如果验证通过
    if (result) {
      if (this.state.editIndex === '') {
        this.setState({
          strategy_data: [policy, ...this.state.strategy_list],
          strategy_list: [policy, ...this.state.strategy_list],
        });
      } else {
        this.state.strategy_list[this.state.editIndex] = {
          ...this.state.strategy_list[this.state.editIndex],
          ...policy,
        };
        this.setState({
          strategy_data: [...this.state.strategy_list],
          strategy_list: [...this.state.strategy_list],
        });
        this.setState({
          editIndex: '',
        });
      }
      Modal.close();
    }
  };

  submit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.strategy_list.length < 1) {
          message.error('试验项策略列表不能为空');
        } else {
          const params = {
            name: values.name,
            app_id: values.app_id,
            event_id: values.event_id,
            product_id: values.product_id || 0,
            strategy_id: this.state.strategy_list[0].strategy_id || 0,
            strategy_list: this.state.strategy_list,
          };
          if (this.actionType === 'update') {
            params.lab_id = this.state.lab_id;
          }
          services[this.api][this.actionType](params).then((data) => {
            if (data.code === 0) {
              message.success(data.msg);
              if (this.actionType === 'add') {
                this.props.history.push(`/strategyLabs/${data.data.lab_id}/detail`);
              } else {
                this.props.history.push(`/strategyLabs`);
              }
            } else {
              message.error(data.msg);
            }
          });
        }
      }
    });
  };

  edit = (record) => {
    this.setState({ editIndex: this.state.strategy_list.findIndex((i) => i === record) });
    Modal.open({
      title: '编辑试验策略',
      width: this.model_width ? this.model_width : '1200px',
      content: (
        <div className='stretegy-content' style={{ marginTop: '-10px' }}>
          <AddPolicy
            {...this.props}
            {...this.state}
            value={cloneDeep(record)}
            wp={{ w: 1200, h: 0.9 * document.body.offsetHeight }}
            usePolicy={(data) => this.usePolicy(data, record.strategy_id)}
            actionType='update'
            localSubmit={true}
            closeModal={() => Modal.close()}
          />
        </div>
      ),
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
    });
  };

  detail = (record) => {
    Modal.open({
      title: '试验策略详情',
      width: this.model_width ? this.model_width : '1200px',
      content: (
        <div className='stretegy-content' style={{ margin: '-10px 0 30px 0' }}>
          <AddPolicy
            {...this.props}
            {...this.state}
            value={JSON.parse(JSON.stringify(record))}
            usePolicy={() => Modal.close()}
            actionType='detail'
            localSubmit={true}
          />
        </div>
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => {
        Modal.close();
      },
    });
  };

  openCopyModal = (record) => {
    const formItems = [
      {
        label: {
          label: '模块名称',
          className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        },
        name: 'model',
        options: {
          initialValue: 2,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' disabled={this.actionType === 'detail'}>
            {/* <Option value={1} key={1}>
              策略实验室(当前模块)
            </Option> */}
            <Option value={2} key={2}>
              策略管理模块
            </Option>
          </Select>
        ),
      },
    ];
    Modal.open({
      title: '复制策略',
      width: '400px',
      content: (
        <div>
          <h4 style={{ marginBottom: '10px' }}>将试验策略复制到：</h4>
          <CustomForm
            closeModal={this.props.closeModal}
            createForm={(ref) => (this.copyForm = ref)}
            formItems={formItems}
            colNum={1}
            hideSubmit={true}
          />
          <p style={{ color: 'red', margin: '-20px 0 20px' }}>通过复制操作可将试验策略复制策略管理模块供线上业务使用</p>
        </div>
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => {
        this.handleCopy(JSON.parse(JSON.stringify(record)));
      },
    });
  };

  removeRuleId = (rules) => {
    return rules.map((item) => {
      const it = Object.assign({}, item);
      delete it.rule_id;
      return it;
    });
  };

  handleCopy = (record) => {
    let val = record;
    if (record.code.includes('_copy_')) {
      val = this.state.strategy_data.find((it) => it.strategy_id === record.strategy_id) || {};
      val.audit_id = 0;
      val.fathers = 0;
    }
    delete val.lab_id;
    const lists = cloneDeep(val);
    let config = {};
    config = {
      ...lists,
      // strategy_config: {
      //   edges: lists.strategy_config.mode.flows.edges,
      //   nodes: lists.strategy_config.mode.flows.nodes,
      // },
      code: this.changeCode(lists.code),
      name: this.changeName(lists.name),
      strategy_id: undefined,
    };
    // // 如果是普通策略
    // if (record.strategy_type === STRATEGY_TYPE._COMMON) {
    //   const rules = (record.strategy_config && record.strategy_config.mode && record.strategy_config.mode.rules) || [];
    //   const code = (record.strategy_config && record.strategy_config.mode && record.strategy_config.mode.code) || [];
    //   const newRules = this.removeRuleId(Object.assign([], rules));
    //   config = {
    //     ...record,
    //     strategy_config: {
    //       ...record.strategy_config,
    //       mode: {
    //         ...(record.strategy_config && record.strategy_config.mode),
    //         code,
    //         rules: newRules,
    //       },
    //     },
    //     name: this.changeName(record.name),
    //     strategy_id: undefined,
    //   };
    // } else {
    //   const nodes = record.strategy_config.nodes.map((item) => {
    //     // 如果是策略节点，则需要做处理
    //     if (item.type === 'strategy') {
    //       const rules = (item.strategy_config && item.strategy_config.mode && item.strategy_config.mode.rules) || [];
    //       const code = (item.strategy_config && item.strategy_config.mode && item.strategy_config.mode.code) || [];
    //       const newRules = this.removeRuleId(Object.assign([], rules));
    //       return {
    //         ...item,
    //         strategy_config: {
    //           ...item.strategy_config,
    //           mode: {
    //             ...(item.strategy_config && item.strategy_config.mode),
    //             code,
    //             rules: newRules,
    //           },
    //         },
    //       };
    //     } else {
    //       return item;
    //     }
    //   });
    //   config = {
    //     ... cloneDeep(record),
    //     // strategy_config: {
    //     //   edges: record.strategy_config.edges,
    //     //   nodes,
    //     // },
    //     name: this.changeName(record.name),
    //     strategy_id: undefined,
    //   };
    // }
    if (this.copyForm.getFieldValue('model') === 1) {
      const strategy_list = [config, ...this.state.strategy_list];
      this.setState({
        strategy_list,
      });
      Modal.close();
    } else {
      // 新建策略管理模块的策略
      services.strategyFlow.add(config).then((res) => {
        if (res.code === 0) {
          message.success('成功');
          Modal.close();
        } else {
          message.error(res.msg);
        }
      });
    }
  };

  delete = (record) => {
    this.setState({
      strategy_list: [...this.state.strategy_list.filter((item) => item.name !== record.name)],
    });
  };

  // 分页回调
  // onChangePagination = pageNumber => {
  //   console.log(pageNumber);
  // };

  render() {
    const formItems = [
      {
        label: {
          label: '试验项名称',
        },
        name: 'name',
        span: 8,
        options: {
          initialValue: this.state.name,
          rules: [
            { required: true, message: '请填写试验项名称' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: <Input placeholder='请填写' />,
      },
      {
        label: {
          label: '所属渠道',
        },
        name: 'app_id',
        span: 8,
        options: {
          initialValue: this.state.app_id,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' disabled={this.actionType === 'update'} onChange={this.appChange}>
            {this.state.applications.map((item, index) => {
              return (
                <Option value={item.app_id} key={item.app_id}>
                  {item.app_name}
                </Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '关联产品',
        },
        name: 'product_id',
        span: 8,
        options: {
          initialValue: this.state.product_id,
        },
        component: (
          <Select
            placeholder='请选择'
            allowClear={true}
            disabled={this.actionType === 'update'}
            onChange={this.productChange}
          >
            {this.state.products.map((item, index) => {
              return (
                <Option value={item.product_id} key={item.product_id}>
                  {item.product_name}
                </Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '关联事件',
        },
        name: 'event_id',
        span: 8,
        options: {
          initialValue: this.state.event_id,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' disabled={this.actionType === 'update'} onChange={this.eventChange}>
            {this.state.events.map((item, index) => {
              return (
                <Option value={item.event_id} key={item.event_id}>
                  {item.event_name}
                </Option>
              );
            })}
          </Select>
        ),
      },
    ];
    const columns = [
      {
        title: '策略名称',
        key: 'name',
        dataIndex: 'name',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className="overflowtext">
                <Button type='link' onClick={() => this.detail(record)}>
                  {text}
                </Button>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '关联策略名称',
        key: 'rawName',
        dataIndex: 'rawName',
        render: (text, record) => {
          return (
            <Tooltip title={this.state.strategy_data[0].name} placement='topLeft'>
              <div className="overflowtext">
                <Button type='link' onClick={() => this.detail(this.state.strategy_data[0])}>
                  {this.state.strategy_data[0].name}
                </Button>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '关联策略版本',
        key: 'version',
        dataIndex: 'version',
        render: (text, record) => {
          return <>{'v' + text}</>;
        },
      },
      // {
      //   title: '策略类型',
      //   key: 'strategy_type',
      //   dataIndex: 'strategy_type',
      //   render: (text, record) => {
      //     return (
      //       <>
      //         {this.props.strategy_type.filter((item) => item.key === record.strategy_type)[0] &&
      //           this.props.strategy_type.filter((item) => item.key === record.strategy_type)[0].value}
      //       </>
      //     );
      //   },
      // },
      // {
      //   title: '优先级',
      //   key: 'prior',
      //   dataIndex: 'prior',
      // },
    ];
    return (
      <div>
        {/* <div style={{ marginBottom: '10px' }}>
          <Button type='primary' onClick={this.openOnlinePolicy}>
            引用线上策略
          </Button>
          <Button className='marl10' onClick={this.openAddPolicy}>
            新建实验策略
          </Button>
        </div> */}
        <div className='box-shadow online-policy-dexy'>
          <div className='filter-area-'>
            <CustomForm
              closeModal={this.props.closeModal}
              createForm={(ref) => (this.form = ref)}
              formItems={formItems}
              onHandleSubmit={Function.prototype}
              hideSubmit={true}
            />
          </div>
          <div className='laboratory-add-button'>
            <Button type='primary' onClick={this.openOnlinePolicy}>
              引用线上策略
            </Button>
            <Button className='marl10' onClick={this.openAddPolicy}>
              新建实验策略
            </Button>
          </div>
          <div style={{ padding: '0 20px' }} className='bg-light'>
            <AddList
              {...this.state}
              {...this.props}
              total={this.state.strategy_list.length}
              list={this.state.strategy_list}
              columns={columns}
              edit={this.edit}
              copy={this.openCopyModal}
              delete={this.delete}
              rowKey='name'
            />
          </div>
          <div className='submit-area-'>
            <Button type='primary' onClick={this.submit}>
              {this.actionType === 'add' ? '保存并试验' : '保存'}
            </Button>
            <Button className='marl10' onClick={() => this.props.history.push('/strategyLabs')}>
              取消
            </Button>
          </div>
        </div>
      </div>
    );
  }
}

export default LabsAdd;
